<template>
  <view class="content">
    <van-nav-bar :title="scrolling? (select ?'购物车' :'购物车管理') : '' " left-arrow @click-left="onClickLeft"> </van-nav-bar>
    <loading :loadingIsShow="loadingIsShow" v-if="!isrefresher"></loading>
    <scroll-view :refresher-enabled="false" class="scroll-content" scroll-y @scroll="scrollPage" show-scrollbar="false">
      <view class="bgCart" v-if="isGood && !loadingIsShow">
        <view class="cartTop">
          <view class="cartAd">
            <view class="cartAd_title" v-if="select">购物车</view>
            <view class="cartAd_title" v-if="!select">购物车管理</view>
            <view v-if="select">
              <view class="admin" @click="onEdit">管理</view>
            </view>
            <view v-if="!select">
              <view class="admin" @click="onOk">完成</view>
            </view>
          </view>
          <view class="jifen">
            <view class="ti">我的积分：</view>
            <view class="jifen_content"><img
                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png" alt=""
                style="height: 13px; width: 13px; margin-right: 6px; " /> {{ myIntegralsBalance || 0 }} </view>
          </view>
          <view class="line"></view>
        </view>
        <view class="cart_content">
          <van-checkbox-group ref="checkboxGroup" :value="checked" :checked="checked" @change="handleCheck">
            <view class="cart listItemLeft list-item" v-for="(item, index) in cartList" :key="index" :id="item.id"
              @click.self="toGoodsDetail(item, index)">
              <van-checkbox v-model="item.status" v-if="showMark" shape="round" @click.stop="onChange('单选', item)"
                :label-disabled="false"
                :disabled="item.onOffShelvesStatus===false && item.status===false ? true : false" use-icon-slot>
                <image
                  :src="(select && (!item.onOffShelvesStatus || item.productStock<=0)) ? disabledIcon : (item.status ? activeIcon : inactiveIcon)"
                  @click.stop="onChange('单选', item)" slot="icon" class="checked-img" />
              </van-checkbox>
              <view class="goods_wraper">
                <view class="wraperTop clearfix">
                  <view class="goodsPic">
                    <img class="img" :src="item.productUrl" mode="widthFix" />
                  </view>
                  <view class="goodsText">
                    <view class="goodsTextTop">
                      <view class="goodsTop">
                        <view class="goods_T" :class="{'noNum':!select}">{{ item.productName }}</view>
                        <view class="wraper_right" v-if="item.onOffShelvesStatus && select">
                          <view class="shuliang_r" v-if="item.productStock > 0 && select">
                              <van-button type="default" class="numBtn" @tap.stop="jian(index, item.id, item.cartNum,$event)" v-if="item.isTag" :disabled="item.cartNum==1"> - </van-button>
                              <van-button type="default" @tap.stop="changeNum(item,$event)" :class="[item.isTag ? 'changeNum' : 'selectNum']"> {{ item.cartNum }} </van-button>
                              <van-button type="default" @tap.stop="add(index, item.id, item.limitedPurchaseQuantity,$event)" v-if="item.isTag" class="numBtn" :disabled="item.cartNum==item.limitedPurchaseQuantity"> + </van-button>
                          </view>
                          <template v-if="item.productStock==0">
                            <view class="reset" v-if="item.productSkuName" @click.stop="showSpecs(item.productId,item)"> 重选</view>
                            <view class="shuliang_r" v-else>
                              <van-button type="default" class="selectNum" disabled> {{ item.cartNum }} </van-button>
                            </view>
                          </template>
                        </view>
                      </view>
                      <view class="goods_specs" @click.stop="showSpecs(item.productId,item)" v-if="item.productSkuName">
                        <view class="goods_specs_text">{{ item.productSkuName }}</view> <van-icon
                          name="arrow-down" size="11" style="margin-left: 7px; display: inline !important; align-items: normal !important; justify-content: normal !important;" />
                      </view>
                    </view>
                    <view class="wraper_bottom">
                      <view class="money">￥{{ item.price }}</view>
                      <view class="jifen_box"><img
                          src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/jinbi_gray1127.png"
                          alt="" style="height: 11px; width: 11px; margin-right: 6px;" /> {{ item.maxUsefulIntegrals }}
                      </view>
                    </view>
                  </view>
                </view>
                <!-- ，预计2024-12-12到货 -->
                <view class="goods_tips" v-if="item.productStock<=0 && item.onOffShelvesStatus"> 商品补货中 </view>
                <view class="goods_tips" v-if="!item.onOffShelvesStatus"> 该产品已下架</view>

              </view>
            </view>
          </van-checkbox-group>
        </view>
      </view>
      <view v-if="!isGood && !loadingIsShow" class="noGoods">
        <view class="cartAd">
          <view class="cartAd_title">购物车</view>
        </view>
        <view class="jifen">
          <view class="ti">我的积分：</view>
          <view class="jifen_content"><img
              src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png" alt=""
              style="height: 13px; width: 13px; margin-right: 6px; " /> {{ myIntegralsBalance || 0 }} </view>
        </view>
        <view class="line"></view>
        <view class="add">
          <van-empty class="custom-image"
            image="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/emptyCart.png"
            description="购物车空空，去添加点什么吧" />
        </view>
        <van-button round @tap="tochecked" class="toCheck">去逛逛</van-button>
      </view>
      <bottom></bottom>
      <van-toast id="van-toast" />
    </scroll-view>
    <template v-if="isGood&& !loadingIsShow">
      <view class="nav_box" v-if="select">
        <van-submit-bar :price="totalAmount" button-text="立即购买" @submit="submitBuy" tip button-type="warning">
          <van-checkbox checked-color="#FF6203" v-model="checkAll" :label-disabled="false" @click="onChange('多选')"
            shape="round" @change="handleCheckAll" use-icon-slot>
            <image @change="handleCheckAll" slot="icon" class="checked-img"
              :src="checkAll ? activeIcon : inactiveIcon" />
            全选
          </van-checkbox>
          <view slot="tip" v-if="totalThresholdAmount && totalThresholdAmount !== '0' && totalAdditionalAmount !=='0'">
            <view class="jo_tips">
              <!-- <view class="tips_text" v-if="discountInfo.difference === 0">
                平台满{{ discountInfo.totalThresholdAmount }}减{{ discountInfo.totalDiscount }}，已减{{
                discountInfo.totalDiscount }}元
              </view>
              <view class="tips_text" v-if="discountInfo.difference > 0">
                平台满{{ discountInfo.totalThresholdAmount }}减{{ discountInfo.totalDiscount }}，还差{{ discountInfo.difference
                }}元可减{{ discountInfo.totalDiscount }}元
              </view> -->
              <view class="tips_text">  {{bestRuleDescription}} </view>
              <view class="tips_button" @click="toJoinOrders()">去凑单</view>
            </view>
          </view>
        </van-submit-bar>
      </view>
      <view class="nav_box" v-if="!select">
        <van-submit-bar price="" button-text="删除所选" button-type="warning" @submit="deteleProduct">
          <view style="display: flex; align-items: center;" class="delete">
            <van-checkbox checked-color="#FF6203" v-model="checkAll" :label-disabled="false" @click="onChange('多选')"
              @change="handleCheckAll" use-icon-slot>
              <image @change="handleCheckAll" slot="icon" class="checked-img"
                :src="checkAll ? activeIcon : inactiveIcon" />
            </van-checkbox>
            <view class="selectedNum" @click="onChange('多选')">已选（{{ selectedRowKeys.length }}）</view>
          </view>
        </van-submit-bar>
      </view>
    </template>
    <!-- 规格选择 -->
    <selectSpecs :showSpecsPopup="showSpecsPopup" :buttonStatus="buttonStatus" @closeSpecsPopup="closeSpecsPopup"
      :parentSign="parentSign" :ebProductAttr="specsList" :ebStoreProduct="ebStoreProduct"
      :ebStoreProductAttrValue="specsPriceList" :ebStoreProductAttrRelationDTO="ebStoreProductAttrRelationDTO"
      :selectSuk="selectSuk" :selectedIds="selectedIds" :cartProInfo="cartProInfo" @changeSpecsPopup="changeSpecsPopup">
    </selectSpecs>
    <van-toast id="van-toast" />
    <van-dialog id="van-dialog" confirm-button-color='#ff6203' />
    <!-- </view> -->

  </view>
</template>
  
<script>
import loading from '@/mycomponents/loading.vue'
import selectSpecs from '@/mycomponents/selectSpecs.vue'
import Toast from '@/wxcomponents/vant/toast/toast'
import Dialog from '@/wxcomponents/vant/dialog/dialog'
import {getCartListApi,checkedShoppingCartItemsApi,cancelShoppingCartItemsApi,deleteShoppingCartItemsApi,setCartSkuNumApi,
  
} from '@/api/shoppingCart'
import { queryProductByIdApi } from '@/api/mall'
import { SOURCE_TYPE } from '@/utils/constant'


export default {

  components: {
      selectSpecs,
      loading
  },
  name: 'cart',
  data() {
    return {
      isrefresher: false,
      loadingIsShow: true,
      loadingIsShowPage: true,
      scrolling:false,
      navBarTitle:'购物车',
      loading:true,
      checked: [], // 已选择的数据的id
      checkAll: false, // 标记是否全选
      selectedRowKeys: [], // 已选择的数据的id
      selectedRows: [], // 已选择的数据
      cartIds:[], //删除接口需要传的id参数
      productId:undefined, //传到规格选择弹窗的 productId
      inactiveIcon:
          'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/notChecked1126.png',
      activeIcon:
          'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/goodsChecked1126.png',
      disabledIcon:'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/disabledIcon.png',

      myIntegralsBalance:'0', //我的积分
      goodsTextWidth:'50%',
      isGood:true,
      cartList: [],
      showMark:true,
      select: true,
      money: 0,
      results: [],

      allchecked:'',
      
      totalAmount:0,
      isShowJ:false,
      showSpecsPopup:false,  //显示规格
      currentItem:0, //商品 右侧数量框框
      parentSign:'cart',
      goodsNum:undefined,
      ebStoreProduct:undefined,
      specsList:[],
      ebStoreProductAttrRelationDTO:[],
      specsPriceList:[],   //规格组合对应的价格
      selectSuk:'',
      cartProInfo:null, 
      allCartIds:[], //购物车所有的id   在取消全选时使用
      bestFullDiscount:undefined,  // 最佳满减规则
      discountInfo:undefined,
      bestRuleDescription:undefined,
      bestThreshold:undefined, // 最佳满减规则的阈值
      totalAdditionalAmount:undefined, //总凑金额
      totalThresholdAmount:undefined, //总满减金额
      hasFullDiscount:false, //是否有满减规格
      isSubmitting:false, //防抖状态标识
      debounceStatus: {
        submitting: false,  // 提交状态
        deleting: false,    // 删除状态
        adjusting: false,    // 数量调整状态
        adding: false,      // 添加状态
        subtracting: false, // 减少状态
      },
      debounceTimers: {
        submit:null,
        detele:null,
        adjust:null,
        add: null,
        subtract: null
      },
      source:SOURCE_TYPE.CART,
    }
  },

  computed: {

    // 过滤出可点击的数据   未进行管理的页面
    newCartList(){  
      return this.cartList.filter(item => item.productStock>0 && item.onOffShelvesStatus!==false)
    },
    // 选出不可点击的数据
    disabledCartList(){  
      return this.cartList.filter(item => item.productStock<=0 || item.onOffShelvesStatus===false)
    },
    filteredArray() {
      if(this.select){
        return this.selectedRows.filter(item => this.disabledCartList.indexOf(item) === -1);
      }
    },
    // formattedCartList() {
    //   return this.cartList.map(item => ({
    //     ...item,
    //     formattedPrice: `￥${item.price}`,
    //     formattedIntegrals: `${item.maxUsefulIntegrals} 积分`
    //   }));
    // }
  },

  watch: {
    cartList: {
      handler(val) {
        console.log(val,'cartList')
        if (!this.select) {  //
          var i = 0
          this.cartList.forEach(item => {
            if (item.status === true) {
              i++
            }
            if (i === this.cartList.length) {   //不需要过滤 下架或售罄商品
              this.checkAll = true
            } else {
              this.checkAll = false
            }
          })
        }
      },
      deep: true
    },
    newCartList: {
      handler(val) {
        console.log(val)
        if (this.select) {
          var i = 0
          this.newCartList.forEach(item => {
            if (item.status === true) {
              i++
            }
            console.log(this.newCartList, 'newCartList')
            this.checkAll = i === this.newCartList.length
 
          })
        }

      },
      deep: true
    },
    disabledCartList: { //有可能存在status为true的商品 影响后续购买商品
        handler(newVal) {
            // 检查disabledCartList中是否有status为true的商品
            const needCancelItems = newVal.filter(item => item.status === true);
            if (needCancelItems.length > 0) {
                const cancelIds = needCancelItems.map(item => item.id);
                this.cancelShoppingCartItemsMethod(cancelIds);
                
                // 更新本地状态
                needCancelItems.forEach(item => {
                    item.status = false;
                });
                
                // 从已选列表中移除
                this.selectedRowKeys = this.selectedRowKeys.filter(id => !cancelIds.includes(id));
                this.selectedRows = this.selectedRows.filter(item => !cancelIds.includes(item.id));
                this.checked = this.checked.filter(id => !cancelIds.includes(id));
            }
        },
        deep: true,
        immediate: true
    },
    checked: {
        handler (val) {
            console.log(val, 'checked')
        }
    },
    selectedRowKeys: {
        handler (val) {
            console.log(val, 'selectedRowKeys')

        }
    },
    selectedRows: {
        handler (val) {
            console.log(val, 'selectedRows')
        }
    }
  },

  onReady(){
    // 静态数据  需要
    // this.loading = false
    // this.cartList.forEach(item => {
    //     this.$set(item, 'status', false)
    //     this.$set(item, 'isTag', false)
    // })
    //this.getCartListMethod()
  },
  onLoad(data){
    console.log(data,'data')
    if(data && data.params){
      this.params = JSON.parse(decodeURIComponent(data.params))
      console.log(this.params, 'params')
      this.source = this.params.source || SOURCE_TYPE.DEFAULT  // 设置默认来源类型
    }
  },

  onShow(){
    // this.clearRowSelection()
    // this.getCartListMethod()
    this.onRefresherMethod()
  },
  methods: {
    onRefresherMethod() {
      if (!this.isrefresher) {
        this.loadingIsShow = true
      }
      this.clearRowSelection()
      const cartList = this.getCartListMethod()
      Promise.all([cartList]).then(() => {
        console.log('所有api加载完成')
        this.loadingIsShow = false
        this.loadingIsShowPage = false
        // 关闭加载状态 (转动的圈)，需要一点延时才能关闭
        this.time = setTimeout(e => {
          this.isrefresher = false
        }, 200)
      })
    },

    onClickLeft(){
      console.log(this.source, 'source')
          const returnMap = {
            [SOURCE_TYPE.CART]: '/pages/shoppingCart/gouwuche',
            [SOURCE_TYPE.ORDER]: '/pages/orders/myOrder',
            // [SOURCE_TYPE.PROMOTION]: '/pages/activity/promotionDetail',
            [SOURCE_TYPE.DETAIL]: '/pages/shangcheng/goodsDetail',
            [SOURCE_TYPE.DEFAULT]: '/pages/orders/myOrder',
            [SOURCE_TYPE.ORDER_DETAIL]: '/pages/orders/orderDetail',
            [SOURCE_TYPE.SURPRISE]: '/pages/surprise/index',
          };
          const targetSource = this.source || SOURCE_TYPE.DEFAULT;
          const targetUrl = returnMap[targetSource] || SOURCE_TYPE.DEFAULT;

          const params = {
              source: targetSource,
          }
          const fullUrl = `${targetUrl}?params=${encodeURIComponent(JSON.stringify(params))}`;
          if (targetSource === SOURCE_TYPE.ORDER_DETAIL || targetSource === SOURCE_TYPE.CART) {
              // 清除页面栈后跳转
              uni.switchTab({ url: '/pages/surprise/index' })
              return;
          }else{
              uni.navigateBack();
          }
    },
    scrollPage(e) {
      console.log(e.detail.scrollTop,this.scrolling)
      if (e.detail.scrollTop > 25 && !this.scrolling) {
        this.scrolling = true
      } else if ((e.detail.scrollTop <= 25 && this.scrolling)|| (e.detail.scrollTop <= 25 && !this.scrolling)) {
        this.scrolling = false
      }
    },
    // 过滤 含有不可点击的商品的Id (下架或者售罄)
    filterData(array1, array2) {
      let arr = []
      arr = array1.filter(item => {
        return !array2.some((val) => {
          return val.id === item.id
        })
      })
      return arr
    },

    // 过滤id  
    filterDataKey(array1, array2) {
      let arr = []
      arr = array1.filter(item => {
        return !array2.some((val) => {
          return val.id === item
        })
      })
      return arr
    },

    // 显示加减
    changeNum(item){
      item.isTag = !item.isTag
    },
    //数字+
    async add(index,id,limitedPurchaseQuantity,e) {
      if (this.debounceStatus.adding) return;
        this.debounceStatus.adding = true;
        this.debounceTimers.add = setTimeout(() => {
            this.debounceStatus.adding = false;
        }, 800);

      console.log(e,'e')
      if(e.stopPropagation) e.stopPropagation()
      const item = this.cartList[index]
      if (item.cartNum >= limitedPurchaseQuantity) {
        return Toast('亲，该宝贝不能购买更多哦')
      }
      // 先更新本地数据
      const originalNum = item.cartNum;
      item.cartNum++;
      //this.$forceUpdate();

      // 后同步到服务器
      try {
        await setCartSkuNumApi({ [id]: item.cartNum });
        this.getCartListMethod(true,index);
        // 接口成功后仅更新当前项
        this.$set(this.cartList, index, { ...item });

      } catch (error) {
        // 失败时回滚本地数据
        item.cartNum = originalNum;
        this.$set(this.cartList, index, { ...item });
        //this.$forceUpdate();
        Toast('更新失败，请重试');
      } finally {
        clearTimeout(this.debounceTimers.add);
        this.debounceStatus.adding = false;
      }
      // let num
      // this.cartList.forEach((item,val)=>{
      //   if(index===val){
      //    num=Number(item.cartNum)
      //    if(limitedPurchaseQuantity === num){
      //     Toast('亲，该宝贝不能购买更多哦')
      //     return false
      //    }else{
      //     num++
      //     item.cartNum=num
      //     const params = {}
      //     params[id] = item.cartNum
      //     console.log(params)
      //     setCartSkuNumApi(params).then(res => {
      //       if (res.code === 200) {
      //         this.getCartListMethod(index)
      //       }
      //     })
      //    }

      //   }
      //   this.goodsNum=num

      // })
      // console.log(num,this.goodsNum,'++++')
    },


    //数字减
    async jian(index,Id,cartNum,e) {
      if (this.debounceStatus.subtracting) return;
        this.debounceStatus.subtracting = true;
        this.debounceTimers.subtract = setTimeout(() => {
            this.debounceStatus.subtracting = false;
        }, 800);

      if(e.stopPropagation) e.stopPropagation()
      
      const item = this.cartList[index];
      if (item.cartNum <= 1) {
        Toast('该宝贝数量不能再减少了哟！');
        return;
      }
      // 本地乐观更新
      const originalNum = item.cartNum;
      item.cartNum--;

      try {
        await setCartSkuNumApi({ [Id]: item.cartNum });
        // 接口成功后仅更新当前项
        this.$set(this.cartList, index, { ...item });
        this.getCartListMethod(true,index);
      } catch (error) {
        // 失败时回滚本地数据
        item.cartNum = originalNum;
        this.$set(this.cartList, index, { ...item });
        Toast('更新失败，请重试');
      } finally {
          clearTimeout(this.debounceTimers.subtract);
          this.debounceStatus.subtracting = false;
      }
    },

    /**
     * 管理模式切换  
     * 单选
     * 多选
     */

    //点击管理  进入管理模式  可删除商品
    onEdit() {
      // 显示删除按钮
      this.select = false
      this.showMark =true
      // 要判断 在管理页面是否是全选
        // 从列表跳转到管理模块时，不可点击的item 也要重新变为false（从管理到列表再到管理）
      this.cartList.map(item => {
        if (item.productStock<=0 || item.onOffShelvesStatus === false) {
          item.status = false
        }
      })
      this.checkAll = this.selectedRowKeys.length === this.cartList.length
    },

    //点击完成  后期完成  点击完成后要对数组重新过滤
    onOk() {
      this.select = true
      this.showMark =true
      console.log(this.checked,'完成',this.selectedRowKeys.length,this.filteredArray)
      this.checked=this.filterDataKey(this.selectedRowKeys,this.disabledCartList)
      this.selectedRows=this.filterData(this.selectedRows,this.disabledCartList)
      this.selectedRowKeys=this.filterDataKey(this.selectedRowKeys,this.disabledCartList)
      console.log(this.selectedRows,this.checked,'过滤',this.disabledCartList,this.newCartList,this.filterData(this.selectedRows,this.disabledCartList))

      // 下架 或者  售罄 状态的商品  变为不可点击状态
      this.cartList.forEach(item => { 
        if (item.productStock<=0 || item.onOffShelvesStatus === false) {
          item.status = false
          this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(item.id),1)
          this.selectedRows.splice(this.selectedRows.indexOf(item),1)
          this.checked.splice(this.checked.indexOf(item.id),1)
        }
      })
      this.checkAll = this.selectedRowKeys.length === this.newCartList.length
    },

    // 提取公共的勾选逻辑
    handleCheckLogic(item, checked) {
      const index = this.selectedRowKeys.indexOf(item.id);

      if (checked && index === -1) { // 如果勾选，则将商品ID和商品信息添加到已选列表中
        this.selectedRowKeys.push(item.id);
        this.selectedRows.push(item);
        // const foundEle = this.disabledCartList.find(ele => ele.id === item.id)
        if(!this.disabledCartList.some(ele => ele.id === item.id)){
          this.checkedShoppingCartItemsMethod([item.id]);
        }
      } else if (!checked && index > -1) { // 如果取消勾选，则从已选列表中移除该商品
        this.selectedRowKeys.splice(index, 1);
        this.selectedRows.splice(index, 1);
        this.cancelShoppingCartItemsMethod([item.id]);
      }
    },
    // 提取公共的全选处理逻辑
    handleSelectAll(checked, isManageMode) {
      const targetList = isManageMode ? this.cartList : this.newCartList;
      const allCheckedIds = targetList.map(item => item.id)
      const allIds = this.newCartList.map(item => item.id)  //排除不可点击元素  只对可点击元素进行操作

      targetList.forEach(item => {  item.status = checked })

      if (checked) {
        this.checked = allCheckedIds;
        this.selectedRows = JSON.parse(JSON.stringify(targetList));
        this.checkedShoppingCartItemsMethod(allIds);
      } else {
        this.checked = [];
        this.checkAll = false;
        this.selectedRows = [];
        this.cancelShoppingCartItemsMethod(allIds);
      }
      this.selectedRowKeys = this.checked;
    },

     // 单选框 选择框
    handleCheck(item, e) {
      console.log(item, e, '单选----')
      const isManageMode = !this.select;
      // 有效性验证
      if (!isManageMode && (item.productStock <= 0 || !item.onOffShelvesStatus)) {
        return Toast('当前商品不可选择');
      }
      item.status = e.detail

      if (!this.select) {  //管理状态
        this.checkAll = this.checked.length === this.cartList.length
      } else {  //非管理状态
        this.checkAll = this.checked.length === this.newCartList.length
      }
      this.handleCheckLogic(item, e.detail)
    },

    // 全选框
    handleCheckAll (val) {
      console.log(val,'全选-----',this.cartList,'11111')
      this.handleSelectAll(val.detail, !this.select)
      // if (!this.select) {  
      //   // 可点击的商品id 
      //   const allCartIds = []
      //   this.newCartList.forEach((y) => {
      //     allCartIds.push(y.id)
      //   })
      //   this.cartList.map(item => {
      //     item.status = val.detail
      //   })
      //   const checkedCount = this.checked.length
      //   if (val.detail) {
      //     this.checked = this.cartList.map((item) => item.id)
      //     this.selectedRows = JSON.parse(JSON.stringify(this.cartList))
      //     this.checkedShoppingCartItemsMethod(allCartIds)
      //   } else if (checkedCount === this.cartList.length) {
      //     this.checked = []
      //     this.checkAll = false
      //     this.selectedRows = []
      //     this.cancelShoppingCartItemsMethod(allCartIds)
      //   }
      //   this.selectedRowKeys = this.checked
      // }else{   // 非管理模式下，只处理可点击的商品
      //   const allCheckedIds =[]
      //   this.cartList.map(item => {
      //     if(item.onOffShelvesStatus!==false && item.isShouQing!==true){
      //       item.status = val.detail
      //     }
      //   })
      //   // 非管理状态 可点击数据
      //   this.newCartList.map(item => {
      //       item.status = val.detail
      //       allCheckedIds.push(item.id)
      //   })
      //   const checkedCount = this.checked.length
      //   if (val.detail) {
      //     this.checked = this.newCartList.map((item) => item.id)
      //     this.selectedRows = JSON.parse(JSON.stringify(this.newCartList))
      //     this.checkedShoppingCartItemsMethod(allCheckedIds)
      //   } else if (checkedCount === this.newCartList.length) {
      //     this.checked = []
      //     this.checkAll = false
      //     this.selectedRows = []
      //     this.cancelShoppingCartItemsMethod(allCheckedIds)
      //   }
      //   this.selectedRowKeys = this.checked

      // }
    },

    // 多选框/单选框后 ---文字的点击事件  +  单选事件、
    // 未点击 管理时要判断disabled    点击之后 不需要判断
    onChange(type, item) {
      console.log(type, 'type', 'onChange')
      if (type === '多选') {
        this.checkAll = !this.checkAll
        console.log(this.checked)
        this.handleSelectAll(this.checkAll, !this.select)

      } else {
        if (this.select && (item.onOffShelvesStatus === false || item.productStock<=0)) {
          return false;
        }
        item.status = !item.status;
        this.handleCheckLogic(item, item.status);
      }
    },
    // 清空已多选项
    clearRowSelection () {
        this.selectedRows = []
        this.selectedRowKeys = []
        this.cartList=[]
    },


    /**
     * 页面功能操作  
     * 删除
     * 结算
     */

    //删除
    deteleProduct() {
      if (this.debounceStatus.deleting) return;

      this.debounceStatus.deleting = true;
      this.debounceTimers.delete = setTimeout(() => {
        this.debounceStatus.deleting = false;
      }, 1000);

      Dialog.confirm({
        message: '确认删除当前所选商品吗？'
      }).then(() => {
        const delCartIds = this.selectedRowKeys
        console.log(this.selectedRowKeys, 'selectedRowKeys', delCartIds, 'cartIds')
        deleteShoppingCartItemsApi(delCartIds).then((res) => {
          console.log(res, 'res')
          if (res.code === 200) {
            // 立即删除本地数据
            this.cartList = this.cartList.filter(item => !delCartIds.includes(item.id));
            this.selectedRowKeys = this.selectedRowKeys.filter(id => !delCartIds.includes(id));
            this.selectedRows = this.selectedRows.filter(item =>!delCartIds.includes(item.id));
            this.checked = this.checked.filter(id =>!delCartIds.includes(id));
            this.checkAll = this.selectedRowKeys.length === this.cartList.length;
            wx.showToast({
                title: '删除成功！',
                icon: 'none',
                duration: 2000
            })
            this.getCartListMethod(true)  //后期要测试
          } else {
            // reject(res)
          }
        })
      })
      .catch(() => {
        console.log('cancel')
      })
      .finally(() => {
        clearTimeout(this.debounceTimers.delete);
        this.debounceStatus.deleting = false;
      });
    },

    // 立即购买
    submitBuy(){
        console.log(this.debounceStatus.isSubmitting,'立即购买','防抖')
        if(this.debounceStatus.isSubmitting) return
        this.debounceStatus.isSubmitting = true
        this.debounceTimers.submit = setTimeout(() => {
          this.debounceStatus.isSubmitting = false;
        }, 500);

        console.log( '立即购买',this.selectedRowKeys,'selectedRowKeys')
        if(this.selectedRows.length>0){
          const params={
            source: SOURCE_TYPE.CART,  // 关键参数
            cartIds: this.selectedRowKeys
          }
          //跳转前重置状态
          this.debounceStatus.isSubmitting = false;
          clearTimeout(this.debounceTimers.submit);
          uni.navigateTo({
            url:
              '/pages/shoppingCart/settlement?params=' +
              encodeURIComponent(JSON.stringify(params))
          })
        }else{
          Toast('你还没有选择宝贝哦')
          this.debounceStatus.isSubmitting = false;
          clearTimeout(this.debounceTimers.submit);

        }
    },

    // 商品详情
    toGoodsDetail(item, index){
        const params={}
        params.item=item
        params.id=item.productId
        params.biaozhi='cart'
        params.onOffShelvesStatus=item.onOffShelvesStatus
        params.source = SOURCE_TYPE.CART;  // 关键参数
        uni.navigateTo({
          url:
            '/pages/shangcheng/goodsDetail?params=' +
            encodeURIComponent(JSON.stringify(params))
        })
    },

    // 去凑单
    toJoinOrders(){
      const params={
        totalAdditionalAmount:this.totalAdditionalAmount,
        totalThresholdAmount:this.totalThresholdAmount,
        pageSign:'cart',
        bestFullDiscount:this.bestFullDiscount,
      }
      uni.navigateTo({
          url:
              '/pages/shangcheng/joinOrders?params=' +
              encodeURIComponent(JSON.stringify(params))
      })
    },

    // 选择规格
    async showSpecs(productId,item){
      console.log(item,'showSpecs')
      if (item.onOffShelvesStatus === false) {
        return Toast('当前商品已下架');
      }
        try {
            // 先获取数据再打开弹窗
            await this.queryProductByIdApiMethod(productId); 
            // 数据就绪后再设置弹窗可见
            this.$nextTick(() => {
                this.productId = productId //接口需要id
                this.selectSuk = item.productSkuName;
                this.cartProInfo = item
                this.showSpecsPopup = true;
            });
        } catch (error) {
            Toast('商品数据加载失败');
        }
    },
    // 关闭规格弹窗
    closeSpecsPopup(){
        this.showSpecsPopup=false
    },
    // 修改确认规格弹窗
    changeSpecsPopup(){
        this.showSpecsPopup=false
        this.getCartListMethod()
    },

    //去逛逛
    tochecked(){
      wx.switchTab({ url: '/pages/surprise/index' })
    },
  /**
   * 接口
   */
    // 购物车列表
    getCartListMethod( i,cartIndex) {
      if (!i) {
        this.selectedRowKeys = []
        this.selectedRows = []
        this.checked = []
        this.loading = true
      }
      return new Promise((resolve, reject) => {
        getCartListApi().then((res) => {
          this.loading = false
          if (res.code === 200) {
            console.log(i,'i')
            if (!i) {
              this.cartList = res.data?.productAndAttrResponse?.responseList || []
              this.isGood = this.cartList.length > 0
              this.myIntegralsBalance = res.data?.integralsBalance || '0'  //我的积分余额
              this.cartList.forEach((item, index) => {
              
                this.$set(item, 'isTag', cartIndex && cartIndex === index)

                if (item.status == true) {
                  this.selectedRowKeys.push(item.id)
                  this.selectedRows.push(item)
                }
                // 使用 find 方法找到满足条件的元素
                const foundEle = item.productAttrValueList.find(ele => ele.id === item.productAttrValueId);
                console.log(foundEle, 'foundEle')
                if (foundEle) {
                  console.log(foundEle.suk, 'foundEle')
                  if(foundEle.suk == ''){
                    item.productSkuName = item.skuName || ''   //规格名称
                  }else{
                    item.productSkuName = foundEle.suk  //规格名称
                  }
                  item.productStock = foundEle.stock  //规格库存
                }
              })
              this.checked = [...this.selectedRowKeys]
              // 自动设置全选状态
              const validItems = this.newCartList.filter(item =>
                item.productStock > 0 &&
                item.onOffShelvesStatus !== false
              )
              this.checkAll = validItems.length > 0 && this.selectedRowKeys.length === validItems.length

              // 同步勾选状态到checked数组
            }
            this.discountInfo = res.data?.fullDiscountMatchedResponse || undefined//满减优惠信息
            this.totalAdditionalAmount = this.discountInfo?.totalAdditionalAmount || '0' //总凑金额
            this.totalThresholdAmount = this.discountInfo?.totalThresholdAmount || '0' //总满减金额
            this.totalAmount = Number(res.data?.fullDiscountMatchedResponse?.totalAmount) * 100 || '0' //总价格

            this.hasFullDiscount = this.discountInfo?.fullDiscountMatchedDetailResponseList?.length > 0 ? true : false
            this.bestRuleDescription = this.discountInfo?.fullDiscountMatchedDetailResponseList?.length === 1 ? this.discountInfo.fullDiscountMatchedDetailResponseList[0].bestRuleDescription : ''
            this.bestFullDiscount = this.discountInfo?.fullDiscountMatchedDetailResponseList?.length === 1 ? this.discountInfo?.fullDiscountMatchedDetailResponseList?.[0]?.bestFullDiscount : undefined
            this.bestThreshold = this.discountInfo?.fullDiscountMatchedDetailResponseList?.length === 1? this.discountInfo?.fullDiscountMatchedDetailResponseList?.[0]?.bestThreshold : undefined

            console.log(this.disabledCartList,'disabledCartList')

            resolve(res)
          } else {
            console.warn('接口返回异常code:', res.code)
            reject(res)
          }
        }).catch(error => {
          console.error('请求捕获错误:', error)
          this.loading = false
          reject(error)
        })
      })
    },

    // 勾选购物车某些商品
    checkedShoppingCartItemsMethod(cartIds){
      return new Promise((resolve, reject) => {
        checkedShoppingCartItemsApi(cartIds).then((res)=>{
          console.log(res,'res')
          if(res.code===200){
              this.getCartListMethod(true);
              resolve(res)
          } else {
              reject(res)
          }
        })
      })
    },

    // 取消勾选商品
    cancelShoppingCartItemsMethod(cartIds){
      return new Promise((resolve, reject) => {
        cancelShoppingCartItemsApi(cartIds).then((res)=>{
          console.log(res,'res')
          if(res.code===200){
              this.getCartListMethod(true);
              resolve(res)
          } else {
              reject(res)
          }
        })

      })
    },

    // 商品信息
    queryProductByIdApiMethod (productId) {
      return new Promise((resolve, reject) => {
          queryProductByIdApi({id: productId}).then((res) => {
              console.log(res)
              if (res.code === 200) {
                  console.log('res-----', res.data)
                  this.ebStoreProduct = res.data?.ebStoreProduct // 轮播图  名称  价格等
                  this.specsList = res.data?.ebProductAttr
                  // this.ebStoreProductAttrRelationDTO=res.data.ebStoreProductAttrRelationDTO
                  this.specsPriceList=res.data.ebStoreProductAttrValue   //规格组合对应的价格

                  resolve(res)
              } else {
                  reject(res)
              }
          })
      })
    },

  },
}
</script>
<style lang="scss" scoped>


.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100vh;
    overflow: hidden;
    z-index: -2;
    background-color: #FFFFFF;
}


.bgCart{
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #FFFFFF;
  height: 100vh;
  // height: calc(100vh - 200px);
  padding-bottom: calc(200rpx + env(safe-area-inset-bottom));
}

// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}
.cartTop {
  padding-left: 24px;
  padding-right: 24px;
  padding-top: 25px;
}


  // 页面标题部分
  .cartAd {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .cartAd_title {
    // font-weight: bold;
    font-size: 30px;
    text-align: left;
    line-height: 30px;
    color: #111111;
  }

  .admin {
    font-size: 12px;
    text-align: left;
    color: #737373;
  }

  .jifen {
    display: flex;
    margin-top: 18px;

    .ti {

      font-size: 16px;
      text-align: left;
      color: #737373;
      line-height: 16px;
    }

    .jifen_content {
      font-weight: bolder;
      font-size: 16px;
      text-align: left;
      color: #111111;
      line-height: 16px;
    }
  }

  // 标题下面的横线
  .line {
    height: 1px;
    width: 100%;
    background: #f0f0f0;
    margin-top: 26px;
    margin-bottom: 26px;
  }

//购物车列表部分  带复选框
.cart_content{
  padding-top: 4px;
  padding-left: 48rpx;
  padding-right: 48rpx;
  // padding-bottom: calc(200rpx + env(safe-area-inset-bottom));
  padding-bottom: calc(260rpx + env(safe-area-inset-bottom));
  margin-bottom: calc(200rpx + env(safe-area-inset-bottom));

  .listItemLeft {
    display: flex;
    align-items: center;
    // justify-content: space-between;
    margin-bottom: 15px;

    .goods_wraper {
      // width: 100%;
      width: calc(100% - 26px);
    }
    // 商品详情 带图片的部分
    .wraperTop {
      display: flex;
      justify-content: space-between;
      width: 100%;
    }

    // 废弃
    .wraper_left{
      display: flex;
      float: left;
      width: 80%;
    }


    .goodsPic {
      // width: 33%;
      width: 222rpx;
      height: 222rpx;
      display: flex;
      justify-content: center;
      flex-direction: column;
      // max-height: 200rpx;
      overflow: hidden;

      img {
        // width: 100%;
        // height: auto;
        width: 100%;
        height: 100%;
        object-fit: cover;
        object-position: center center;
      }
    }

    // 商品提示信息  售罄 或者下架
    .goods_tips {
      margin-top: 6px;
      font-size: 11px;
      text-align: left;
      color: #888888;
      line-height: 11px;
    }
  }

}


.goodsText {
    // position: relative;
    // width: calc(67% - 14px);
    width: calc(100% - 250rpx);
    margin-left: 28rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding-top: 10rpx;
    padding-bottom: 12rpx;
    text-align: left;

    .goodsTextTop{
      width: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    .goodsTop {
        // position: absolute;
        // top: 2%;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

    
        .goods_T {
          font-size: 28rpx;
          text-align: left;
          color: #111111;
          // line-height: 28rpx;
          max-width: 74%;
          white-space: nowrap;
          /* 防止文本换行 */
          overflow: hidden;
          /* 超出部分隐藏 */
          text-overflow: ellipsis;
          /* 显示省略号 */
    
        }
        .noNum{  //不显示右侧的数量时，需要设置的样式 标题全部显示，最大宽度为100%
          max-width: 100%;
        }
    
        .wraper_right {
          // float: right;

          .shuLiang {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin: 0px 12rpx;
            padding-left: 12rpx;
            padding-right: 12rpx;
            line-height: 18px;
            border-radius: 2px;
            border: 1px solid #D4D4D4;
            font-size: 24rpx;
            color: #111111;

            
            .numBox{
              width: 44rpx;
              text-align: center;
            }
          }
          .shuliang_r {
            width: 100%;
            padding-left: 12rpx;
            padding-right: 12rpx;
            border-radius: 2px;
            // border: 1px solid #D4D4D4;
            font-size: 24rpx;
            color: #111111;
            display: flex;
            align-items: center;
          }
          .shuliang .numBtn{
            width: 36rpx;
            height: 36rpx;
            // line-height: 36rpx;
            cursor: pointer;
          }
          .shuliang .changeNum{
            min-width: 44rpx;
            height: 36rpx;
            // line-height: 36rpx;
            cursor: pointer;
          }
          .reset {
            font-size: 24rpx;
            line-height: 24rpx;
            text-align: center;
            color: #FF6203;
          }
        }
      }



    .goods_specs {
      // position: absolute;
      // top: 30%;
      // padding-top: 24rpx;
      margin-top: 22rpx;
      // width: 85%;
      width: calc(100% - 12rpx); /* 改为100%让父容器控制总宽度 */ 
      font-size: 24rpx;
      text-align: left;
      color: #666666;
      display: flex;
      // align-items: center;
      gap: 10rpx; /* 添加间距 */
    }
  
    .goods_specs_text{
      // flex: 1; /* 自动填充剩余空间 */
      // max-width: 75%;
      display: -webkit-box;
      -webkit-line-clamp: 2;
       /* 标准方案（未来可能支持） */
      line-clamp: 2; /* 标准属性，部分浏览器已支持 */
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
      line-height: 1.5; /* 添加合适的行高 */
      max-height: 3em; /* 根据行高计算最大高度 */
      min-width: 0; /* 关键修复：防止flex item溢出 */
      word-break: break-all; /* 允许单词内换行 */
    }

    .wraper_bottom{
      display: flex;
      align-items: center;

    .money{
      font-size: 28rpx;
      text-align: left;
      color: #737373;
    }
    
    .jifen_box{
      font-weight: bolder;
      font-size: 28rpx;
      text-align: left;
      color: #888888;
      margin-left: 12rpx;
      //line-height: 28rpx;
      // height: 28rpx;
    }
  }
}
.goodsCard{
  display: flex;
  justify-content: space-between;
}


//防止父元素高度塌陷
.clearfix::after {
    content: "";
    display: table;
    clear: both;
}



.checked-img {
    height: 16px;
    width: 16px;
}

.joinOrder_tips{
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    bottom: 110px; 
    width: calc(100% - 48px);
    height: 35px;
    padding-left: 24px;
    padding-right: 24px;

    line-height:24rpx;
    font-size:24rpx;
    text-align: left;
    color: #FF6203 ;

    background:#FFF9F7;
  }



.noGoods{
  display: flex;
  flex-direction: column;
  text-align:center;
  background-size: 100%;
  margin-top: 24px;
  padding-left: 48rpx;
  padding-right: 48rpx;
}
::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep .van-icon {
    color: #242629 !important;
}

::v-deep .van-nav-bar__title {

    font-size: 28rpx;
    color: #333333;
}

::v-deep .bar-class, .van-submit-bar__bar{
  display: flex;
  justify-content: space-between !important;
  border-top: 1px solid #f9f9f9 !important;
  // padding-top: 20px !important;
}
::v-deep .van-submit-bar__tip {
    color: #FF6203 !important;
    background-color:#FFF9F7 !important;
    padding-left: 24px !important;
    padding-right: 24px !important;
    line-height: 35px !important;
    padding-top: 0 !important; 
    padding-bottom: 0!important;
}
// 合计价格的颜色
::v-deep .van-submit-bar__price{
  color: #FF6203 !important;
}

.jo_tips{
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 35px;
  line-height: 24rpx;
  font-size:24rpx;
  text-align: left;
  color: #FF6203 ;

  background:#FFF9F7;

}
.tips_button{
  padding-left:11px;
  padding-right: 11px;
  // height: 40px;
  border-radius:20px;
  line-height: 20px;
  border: 1px solid #FF6203;
}

// 已选数量
.selectedNum{
  font-size: 22rpx;
  text-align: left;
  color: #888888;
  line-height: 17px;
  height: 17px;
}
.list-item {
    transition: opacity 0.3s ease;  // 添加渐变过渡
    backface-visibility: hidden;   // 隐藏背面渲染
}
// 组件规格  底部的线
::v-deep .van-goods-action, .van-goods-action--safe{
    border-top: 1px solid #f9f9f9 !important;
}

::v-deep .van-button--warning{
  background-color: #FF6203;
}
// ::v-deep .van-button--danger {
//   background-color: #FF6203 !important;
//   width: 60%;
//   border: none;
// }

::v-deep .van-icon-success{
  color: #ffffff !important;
}
::v-deep .van-checkbox__icon-wrap {
    height: 32rpx!important;
    flex: none !important;
    display: flex !important;
    align-items: center !important;
}
::v-deep .selectNum .van-button {
  height: 36rpx !important;
  width: 58rpx !important;
  // line-height: 36rpx !important;
  cursor: pointer;
}

::v-deep .numBtn .van-button {
  height: 36rpx !important;
  width: 36rpx !important;
  // line-height: 36rpx !important;
  cursor: pointer;
}
::v-deep .changeNum .van-button {
  height: 36rpx !important;
  width: 44rpx !important;
  // line-height: 36rpx !important;
  cursor: pointer;
} 

::v-deep .numBtn,.changeNum .van-button--default {
  border: none;
}
::v-deep .toCheck .van-button--default{
    background-color: #FF6203 !important;
    width: 100%!important;
    color: #FFFFFF;
}
::v-deep.van-checkbox__label:empty {
    margin: 0;
    padding: 0 !important;
}

// 规格箭头
::v-deep .goods_specs .van-icon {
    display: inline !important; /* 覆盖flex布局 */
    align-items: normal !important;
    justify-content: normal !important;
}
</style>